﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using webtracuudiem.Truyxuatdulieu;

namespace webtracuudiem
{
    public partial class LoginControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.User.Identity.IsAuthenticated == true)
            {
                lblUsername.Text = Page.User.Identity.Name;
                mvLogin.SetActiveView(viewDaDangNhap);
            }
            else
                mvLogin.SetActiveView(viewChuaDangNhap);
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (Membership.ValidateUser(txtUserName.Text, txtPassword.Text))
            {
                FormsAuthentication.SetAuthCookie(txtUserName.Text, chkRemember.Checked);

                //if (Page.User.IsInRole("admin"))
                //    Response.Redirect("/Admin/TaoTaiKhoan.aspx");
                //if (Page.User.IsInRole("sv"))
                //    Response.Redirect("/TraCuuDiem.aspx");
                string username = txtUserName.Text;
                string password = txtPassword.Text;
                string sqlSelect = "select maquyen from QuyenNguoiDung where Username=@Username";
                DataTable tblKetQua = TienIchSql.ChayLenhSelectDuLieu(sqlSelect, "@Username", username);
                string[] dsQuyen = new string[tblKetQua.Rows.Count];

                for (int i = 0; i < tblKetQua.Rows.Count; i++)
                {
                    dsQuyen[i] = ((string)tblKetQua.Rows[i]["MaQuyen"]).ToLower();
                }
                if (dsQuyen.Contains("admin"))
                    Response.Redirect("/Admin/Qlytaikhoan.aspx");
                if (dsQuyen.Contains("sv"))
                    Response.Redirect("/TraCuuDiem.aspx");
                if (dsQuyen.Contains("gv"))
                    Response.Redirect("/Nhapdiem.aspx");
                if (dsQuyen.Contains("pdt"))
                    Response.Redirect("/TrangPhongDaoTao.aspx");
                if (dsQuyen.Contains("cths"))
                    Response.Redirect("/CTHS.aspx");
                
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, chkRemember.Checked);
            }
            else
            {
                lblThongBao.Text = "Tên đăng nhập hoặc mật khẩu không đúng!";
            }
        }

        protected void btnThoat_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            Response.Redirect("/Default.aspx");
        }
    }
}